package output

import (
	"chainmaker.org/chainmaker/smarteditor/conf"
	"chainmaker.org/chainmaker/smarteditor/util"
	"encoding/json"
	"net/http"
	"path/filepath"
)

type GetCodeByHashRequest struct {
	UserId       string `json:"userId"`
	Hash         string `json:"hash"`
	ContractName string `json:"contractName"`
}

type GetCodeByHashResponse struct {
	File []byte `json:"file"`
}

//GetContractCodeByHashHandler get contract source code
func GetContractCodeByHashHandler(w http.ResponseWriter, r *http.Request) {

	requestParam := &GetCodeByHashRequest{}
	if err := json.NewDecoder(r.Body).Decode(requestParam); err != nil {
		log.Errorf("GetContractByHashHandler decode parameter fail, param:%v, err:%v", requestParam, err)
		http.Error(w, "parameter error", http.StatusBadRequest)
		return
	}
	log.Debugf("GetContractByHashHandler reauest param. parameter: %s", requestParam)

	if util.AnyEmpty(requestParam.Hash, requestParam.UserId, requestParam.ContractName) {
		log.Errorf("GetContractByHashHandler illegal paramter. param: %v", requestParam)
		http.Error(w, "parameter error", http.StatusBadRequest)
		return
	}

	user := conf.GetUser(requestParam.UserId)
	if user == nil {
		log.Errorf("GetContractByHashHandler user not fount. user id:%v", requestParam.UserId)
		http.Error(w, "parameter error", http.StatusBadRequest)
		return
	}

	deployDir := conf.GetDeployDir(conf.GetUserWorkspace(requestParam.UserId))
	directoryName := requestParam.Hash
	source7zName := conf.GetSource7zName()
	source7zFile := filepath.Join(deployDir, requestParam.ContractName, directoryName, source7zName)
	if !util.FileExists(source7zFile) {
		log.Errorf("GetContractByHashHandler file not fount. file:%s", source7zFile)
		http.Error(w, "parameter error", http.StatusBadRequest)
		return
	}

	w.Header().Set("Content-Disposition", "attachment; filename="+source7zName)
	w.Header().Set("Content-Type", "application/7z")
	http.ServeFile(w, r, source7zFile)
}
